<template>
  <el-dialog
      :title="form.buildingId ? '编辑楼宇' : '新增楼宇'"
      v-model="visible"
      :close-on-click-modal="false"
      draggable
      width="600px"
  >
    <el-form
        ref="dataFormRef"
        :model="form"
        :rules="dataRules"
        label-width="90px"
        v-loading="loading"
    >
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="楼宇名称" prop="buildingName">
            <el-input v-model="form.buildingName" placeholder="请输入楼宇名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="楼宇层数" prop="floors">
            <el-input
                v-model="form.floors"
                placeholder="请输入楼宇层数"
                type="number"
                min="1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="楼宇高度" prop="height">
            <el-input
                v-model="form.height"
                placeholder="请输入楼宇高度"
                type="number"
                min="0"
                step="0.1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="楼宇面积" prop="area">
            <el-input
                v-model="form.area"
                placeholder="请输入楼宇面积"
                type="number"
                min="0"
                step="0.01"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="建成时间" prop="completionTime">
            <el-date-picker
                v-model="form.completionTime"
                type="date"
                placeholder="请选择建成时间"
                value-format="YYYY-MM-DD"
                :max-date="new Date()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remark">
            <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
                rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BuildingDialog">
import { useMessage } from "/@/hooks/message";
import { getBuilding, addBuilding, updateBuilding } from '/@/api/building/building';
import { ref, reactive, nextTick } from 'vue';
const emit = defineEmits(['refresh']);

// 定义楼宇信息类型
interface BuildingForm {
  buildingId: string;
  buildingName: string;
  floors: number | string;
  height: number | string;
  area: number | string;
  completionTime: string;
  remark: string;
}

// 表单引用
const dataFormRef = ref();
// 弹窗显示状态
const visible = ref(false);
// 加载状态
const loading = ref(false);

// 表单数据
const form = reactive<BuildingForm>({
  buildingId:'',
  buildingName: '',
  floors: '',
  height: '',
  area: '',
  completionTime: '',
  remark: '',
});

// 校验规则
const dataRules = ref({
  buildingName: [{ required: true, message: '楼宇名称不能为空', trigger: 'blur' }],
  floors: [{ required: true, message: '楼宇层数不能为空', trigger: 'blur' }],
  height: [{ required: true, message: '楼宇高度不能为空', trigger: 'blur' }],
  area: [{ required: true, message: '楼宇面积不能为空', trigger: 'blur' }],
  completionTime: [{ required: true, message: '建成时间不能为空', trigger: 'change' }],
  remark: [{ max: 500, message: '备注不能超过500个字符', trigger: 'blur' }]
});

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true;
  // 重置表单
  nextTick(() => {
    dataFormRef.value?.resetFields();
    // 清空表单数据
    Object.keys(form).forEach(key => {
      form[key as keyof BuildingForm] ='';
    });

    // 如果有ID，获取详情
    if (id) {
      form.buildingId = id;
      getBuildingData(id);
    }
  });
};

// 取消按钮
const handleCancel = () => {
  visible.value = false;
  // 重置表单
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });
};

// 提交表单
const onSubmit = async () => {
  // 表单验证
  const valid = await dataFormRef.value?.validate().catch(() => false);
  if (!valid) return;

  try {
    loading.value = true;
    // 根据是否有ID判断是新增还是编辑
    if (form.buildingId) {
      await updateBuilding(form);
      useMessage().success('修改成功');
    } else {
      await addBuilding(form);
      useMessage().success('添加成功');
    }
    visible.value = false;
    emit('refresh'); // 通知父组件刷新列表
  } catch (err: any) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 获取楼宇详情
const getBuildingData = (id: string) => {
  loading.value = true;
  getBuilding(id).then((res: any) => {
    Object.assign(form, res.data);
  }).catch((err: any) => {
    useMessage().error(err.msg || '获取数据失败');
  }).finally(() => {
    loading.value = false;
  });
};

// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>
